package springboot.controller;

import springboot.dao.RoleDao;
import springboot.domain.Role;
import springboot.domain.User;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springboot.service.UserService;

import java.util.List;

@RestController
@RestControllerAdvice
@RequestMapping("/user")
public class UserController {
    Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private RoleDao roleDao;

    @PostMapping("/addUser")
    @RequiresPermissions("user:post")
    public String addUser(@RequestParam("username")String username,@RequestParam("password")String password,@RequestParam("role_id")int role_id){
        Role role = roleDao.getRolesById(role_id);
        User user = new User(username,password);
        user.setRole(role);
        return userService.addUser(user);
    }
    @GetMapping("/users")
    @RequiresPermissions("user:get")
    public List<User> getAllUsers(){
        return userService.getUsers();
    }
    @GetMapping("/users/{id}")
    @RequiresPermissions("user:get")
    public User getUserById(@PathVariable("id")int id){
        User user = userService.getUserById(id);
        if(user!=null) {
            return user;
        } else{
            throw new RuntimeException("用户：" + id + "不存在！");
        }
    }
    @PutMapping("/users/{id}")
    @RequiresPermissions("user:put")
    public String updateUserById(@PathVariable(value = "id")int id, @RequestParam("password")String password){
        User user = new User(id,password);
        return userService.updateUser(id,user);
    }
    @DeleteMapping("/users/{id}")
    @RequiresPermissions("user:delete")
    public String deleteUserById(@PathVariable("id")int id){
        return userService.deleteUserById(id);
    }
    @GetMapping("/usersName/{id}")
    public String getUserNameById(@PathVariable("id")int id){
        return userService.getNameById(id);
    }
}
